<?php

class User extends CActiveRecord {
        public function rules(){
		return array(
			array('username, roleId, email', 'required', 'on'=>'create, update'),
                        array('username, email', 'unique', 'on'=>'create, update'),
                        array('email', 'email'),
                        array('id, username, roleId, email', 'safe', 'on'=>'search')
		);
	}
    
        public static function model($className=__CLASS__){
            return parent::model($className);
        }

        public function tableName(){
            return 'users';
        }
        
        public function attributeLabels() {
                return array(
                        'roleId'=>'Role'
                );
        }
        
        protected function beforeSave() {
                $this->password=  md5($this->username);
            
                return parent::beforeSave();                
        }
        
        public function search(){
                $criteria=new CDbCriteria();
                if($this->id){
                        $criteria->addCondition('id='.$this->id);
                }
                
                if($this->username){
                        $criteria->addCondition('username LIKE "%'.$this->username.'%"');
                }
                
                if($this->email){
                        $criteria->addCondition('email LIKE "%'.$this->email.'%"');
                }
                
                if($this->roleId){
                        $criteria->addCondition('roleId='.$this->roleId);
                }
            
                return new CActiveDataProvider('User', array(
                        'criteria'=>$criteria
                ));
        }
        
        public function getRole(){
                return Role::model()->findByPk($this->roleId);
        }
}

?>
